import pandas
from tkinter import messagebox
from Model import *
from View import *

class CopyController:
    def __init__(self):
        self.state = False

    def _readexcel2(self):
        if len(excel2CopyChooser.filenames) > 0 :
            return excel2CopyChooser.selected()[excel2CopyChooser.filenames[0]]
        else:
            return "None"
        pass

    def _showinputError(self):
        if RF.wspointer !='主菜单':
            messagebox.showinfo("文件地址无效",
                                "请选择需要处理的EXCEL文件！")
            copyMenu.ws.focus_force()
            print("录入地址无效！")

    def getexcel2(self):
        excel2CopyChooser.choose()
        print(self._readexcel2())
        if self._readexcel2() != "None":
            excel2.inputexcel(self._readexcel2())
            print(excel2.df)
            print(excel2.cindex)
            toCopyIndexChooser.resetmenu("抄写哪一列？", excel2.cindex)
            copyPreviewTable.loaddata(excelCopyResult.df)
        else:
            self._showinputError()

    def _copy(self):
        excelCopyResult.createexcel(df=excel0.df)
        cindex = copyIndexChooser.getvalue()
        cindex2copy = toCopyIndexChooser.getvalue()
        print(f"从表2的{cindex2copy}列抄写，以{cindex}为索引")
        result = excelCopyResult.copyindex(excel2, cindex, cindex2copy)
        return result

    def preview(self):
        state = self._copy()
        if state:
            copyPreviewTable.loaddata(excelCopyResult.df)
            copyPreviewWindow.open()
        else:
            print("抄写失败！请重新选择索引列与抄写列")
            messagebox.showinfo(title='操作失败', message="抄写失败！请重新选择索引列与抄写列")
            copyMenu.ws.focus_force()

    def save(self):
        state = self._copy()
        if state:
            if excel0.ftype == 'xlsx':
                name = '抄写表格_' + excel0.fname[:] + '.xlsx'
            else:
                name = '抄写表格_' + excel0.fname[:].rpartition('.')[0] + '.xlsx'
            ExcelSaver.setinitialfile(name)
            try:
                path = ExcelSaver.save()[1]
                print(excelCopyResult.df)
                excelCopyResult.saveexcel(path)
                messagebox.showinfo("保存提示","保存成功！")
                copyMenu.ws.focus_force()
            except:
                messagebox.showinfo("地址无效警告",
                                    "请重新选择保存位置，并填写正确的文件后缀名")
                copyMenu.focus_force()

        else:
            print("抄写失败！请重新选择索引列与抄写列")
            messagebox.showinfo(title='操作失败', message="抄写失败！请重新选择索引列与抄写列")
            copyMenu.ws.focus_force()


copyController = CopyController()
excel2CopyChooser.resetcommand(command=copyController.getexcel2)
copyPreviewButton.configure(command=copyController.preview)
copySaveButton.configure(command=copyController.save)